﻿#!/usr/bin/env python
#
# GAE-Appengine-CMS
# Copyright (c) 2010 ITBelt (itbelt.com)
# Licensed under the GPL license:
# http://www.gnu.org/licenses/gpl.html
# 

import random
import string
import datetime
import sys

from google.appengine.ext import db
from google.appengine.api import memcache
from django.utils import simplejson
from google.appengine.ext.db import djangoforms

def monkey_patch(name, bases, namespace):
  assert len(bases) == 1, 'Exactly one base class is required'
  base = bases[0]
  for name, value in namespace.iteritems():
    if name not in ('__metaclass__', '__module__'):
      setattr(base, name, value)
  return base 

class PatchClass(db.Model):
    __metaclass__ = monkey_patch  
    
    def toJSON(self):
        o=[[m,getattr(self, m)] for m in dir(self) if not(m[:1]=='_' or callable(getattr(self, m)) )]
        s='{'
        s+='"id":"%s",' %(self.key().id())
        for p in o:
            if type(getattr(self, p[0]))==datetime.datetime:
              s+='"%s":"%s",' %(p[0],p[1])
            else:    
              s+='"%s":%s,' %(p[0],simplejson.dumps(p[1])) 
        s=s[:-1]+'}'
        return s
    def clear_cache(self):
        pass
    
 
class News(db.Model):
    """Represents a single news."""
    title = db.StringProperty(required=True)
    body = db.TextProperty(required=True)
    seo_path=db.StringProperty(required=True)
    created = db.DateTimeProperty(auto_now_add=True)
    updated = db.DateTimeProperty(auto_now=True)
    
    def clear_cache(self):       
        key = 'news_seo_%s' % self.seo_path
        memcache.delete(key)
    
    @staticmethod
    def get_short_news_lists():
        query = db.Query(News).order('-created')
        return query.fetch(5)
    
    @staticmethod
    def getByUrl(path):
        key = 'news_seo_%s' % path
        tmpl = memcache.get(key)
        if tmpl:
            return tmpl
        else:
            tmpl = News.gql("WHERE seo_path=:1", path).get()
            if tmpl:
                memcache.add(key, tmpl, 300)
                
        return tmpl

class NewsForm(djangoforms.ModelForm):
    class Meta:
        model = News
        exclude = ['created','updated']

class PageTemplate(db.Model):
    name=db.StringProperty(required=True)
    seo_path=db.StringProperty()
    title = db.StringProperty(required=True)
    type = db.StringProperty(required=True, default='control',choices=['page', 'control'])
    body = db.TextProperty(required=True)
    created = db.DateTimeProperty(auto_now_add=True)
    updated = db.DateTimeProperty(auto_now=True)
    controls= db.StringProperty()
    
    def clear_cache(self):       
        keys = ('tmpl_%s' % self.name, 'tmpl_seo_%s' % self.seo_path)
        memcache.delete_multi(keys)
    
    @staticmethod
    def getByName(name):
        key = 'tmpl_%s' % name
        tmpl = memcache.get(key)
        if tmpl:
            return tmpl
        else:
            tmpl = PageTemplate.gql("WHERE name=:1", name).get()
            if tmpl:
                memcache.add(key, tmpl)
                
        return tmpl
    
    @staticmethod
    def getByUrl(path):
        key = 'tmpl_seo_%s' % path
        tmpl = memcache.get(key)
        if tmpl:
            return tmpl
        else:
            tmpl = PageTemplate.gql("WHERE seo_path=:1", path).get()
            if tmpl:
                memcache.add(key, tmpl)
                
        return tmpl
    
class PageTemplateForm(djangoforms.ModelForm):
    class Meta:
        model = PageTemplate
        exclude = ['created','updated']
        
class SiteMap(db.Model):
    title=db.StringProperty(required=True,)
    seo_path=db.StringProperty(required=True,)
    type = db.StringProperty(required=True, default='page',choices=['page', 'folder'])
    parent_node = db.SelfReferenceProperty("parent", "children")
    created = db.DateTimeProperty(auto_now_add=True)
    updated = db.DateTimeProperty(auto_now=True)
    page=db.StringProperty()
    
    @staticmethod
    def _get_node_(path,parent):
        if parent:
            sid=parent.key().id()
        else:
            sid='None'
        key = 'smn_%s_%s' %(sid,path)
        node = memcache.get(key)
        if not node:
            node = SiteMap.gql("WHERE seo_path=:1 and parent_node=:2", path, parent).get()
            if node:
                memcache.add(key, node,)
                
        return node
    
    @staticmethod
    def getMap(path):
        p=path.split('/')
        map=[]
        parent=None
        for np in p:
            node=SiteMap._get_node_(np,parent)
            if node:
                parent=node
                map.append(node)
            else:
                return None
        return map
        
class SiteMapForm(djangoforms.ModelForm):
    class Meta:
        model = SiteMap
        exclude = ['created','updated']